package com.le.tester.javaThink.fourth.concurrency;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/12/24 16:40
 * description：哲学家使用筷子
 */
public class Philosopher implements Runnable {

    private Chopstick left;
    private Chopstick right;

    private final int id;
    //思考的因素个数
    private final int ponderFactor;

    public Philosopher(Chopstick left, Chopstick right, int id, int ponderFactor) {
        this.left = left;
        this.right = right;
        this.id = id;
        this.ponderFactor = ponderFactor;
    }

    private Random random = new Random(47);

    private void pause() throws InterruptedException {
        //如果此时不需要思考
        if (ponderFactor == 0) return;

        TimeUnit.MILLISECONDS.sleep(random.nextInt(ponderFactor * 250));
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println(this + " " + "thinking");
                pause();
                System.out.println(this + " " + "grabbing right");
                right.take();
                System.out.println(this + " " + "grabbing left");
                left.take();
                System.out.println(this + " " + "eating");
                pause();
                right.drop();
                left.drop();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public String toString() {
        return "Philosopher{" +
                "left=" + left +
                ", right=" + right +
                ", id=" + id +
                ", ponderFactor=" + ponderFactor +
                ", random=" + random +
                '}';
    }
}
